package com.yunbao.core.shiro.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.yunbao.project.entity.Merchant;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.Objects;

/**
 * JWT工具类
 *
 * @author 安能
 * @date 2019年9月17日00:17:52
 **/
public class JwtUtil {

    private static final long EXPIRE_TIME = 5 * 60 * 1000;

    /**
     * 校验token是否正确
     *
     * @param token  密钥
     * @param secret 用户的密码
     * @return 是否正确
     */
    public static boolean verify(String token, Merchant merchant) {
        try {
            //根据密码生成JWT效验器
            Algorithm algorithm = Algorithm.HMAC256(merchant.getPassword());
            JWTVerifier verifier = JWT.require(algorithm)
                    .withClaim("id", merchant.getId())
                    .withClaim("username", merchant.getUserName())
                    .build();
            //效验TOKEN
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的Id信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static Integer getId(String token) {


        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asInt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }
    /**
     * 获得token中的Id信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static Integer getId() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(servletRequestAttributes).getRequest();
        String token = request.getHeader("token");
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("id").asInt();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    /**
     * 把token转换成商家
     *
     * @return token中包含的用户名
     */
    public static Merchant getMerchant(String token) {
        try {

            DecodedJWT jwt = JWT.decode(token);

            return new Merchant()
                    .setId(jwt.getClaim("id").asInt())
                    .setUserName(jwt.getClaim("username").asString())
                    ;

        } catch (JWTDecodeException e) {
            return null;
        }
    }


    /**
     * 生成签名,5min后过期
     *
     * @param username 用户名
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(Merchant merchant) throws UnsupportedEncodingException {
//        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(merchant.getPassword());
        // 附带username信息
        return JWT.create()
                .withClaim("id", merchant.getId())
                .withClaim("username", merchant.getUserName())
//                .withExpiresAt(date)
                .sign(algorithm);

    }
}